<template>
<div>

<!-- 年月 -->
<el-row class="fc-toolbar">
	<el-col :span="3" class="pointer" @click.native="pre">
		<i class="el-icon-arrow-left"></i>
		{{mmm.m == 0 ? 12 : mmm.m}}月
	</el-col>
	<el-col :span="3" class="pointer" @click.native="batchSetup">
		批量设置
	</el-col>
	<el-col :span="12" class="h1" style="margin-top:-7px;">
		{{mmm.y}}年{{mmm.m + 1}}月
	</el-col>
	<el-col :span="3">
		&nbsp;
	</el-col>
	<el-col :span="3" class="pointer" @click.native="back">
		{{mmm.m + 2 == 13 ? 1 : mmm.m + 2}}月
		<i class="el-icon-arrow-right"></i>
	</el-col>
</el-row>
<el-row>
	<el-table
	    :data="mmm.data"
	    border
	    @cell-click="cellClick"
	    size="mini"
	    style="width: 100%">
	    <el-table-column
	    	v-for="(w, index) in week"
	        :label="w"
	    >
	    	<template slot-scope="scope">
	    		{{scope.row[index].label}}
	    		<div class="haha">
	    		<div v-for="l in scope.row[index].labelarr" >
	    			{{l.show}}
	    		</div>
	    		</div>
	    	</template>
	    </el-table-column>
	   
	</el-table>

</el-row>



<el-dialog title="设置价格" :visible.sync="batchSetupFormVisible" width="70%">
  <el-form :model="batchSetupForm" label-width="180px">
  	
    <el-form-item label="选择范围：" v-if="clickWhat == 0">
      	<daterange v-bind:se.sync="batchSetupForm.s_e" type="daterange"></daterange>
    </el-form-item>

    <el-form-item label="选择星期：" v-if="clickWhat == 0">
	    <el-checkbox v-for="(w, index) in weekDay" :key="index" v-model="w.value">
	    	周{{w.day}}
	    </el-checkbox>
    </el-form-item>

    <el-form-item label="日期：" v-if="clickWhat == 1">
    	{{batchSetupForm.date}}
    </el-form-item>

    <el-form-item label="商城价格：" >
      	<el-input v-model="batchSetupForm.guide_price" style="width:300px;"></el-input>
    </el-form-item>

    <el-form-item label="成本价格：" >
      	<el-input v-model="batchSetupForm.cost_price" style="width:300px;"></el-input>
    </el-form-item>

    <el-form-item label="库存：" >
      	<el-input v-model="batchSetupForm.num" style="width:300px;"></el-input>
    </el-form-item>
    
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="batchSetupFormVisible = false">取 消</el-button>
    <el-button v-if="clickWhat == 0" type="primary" @click="batchSetupSave">确 定</el-button>
    <el-button v-if="clickWhat == 1" type="primary" @click="cellSave">确 定</el-button>

  	<el-button 
  	v-if="clickWhat == 0" 
  	type="danger" @click="batchSetupDel">删除价格</el-button>

  	<el-button 
  	v-if="clickWhat == 1 && dp[batchSetupForm.date] != undefined" 
  	type="danger" @click="cellDel">删除价格</el-button>
  </div>
</el-dialog>

</div>
</template>

<script>

import { mapGetters } from 'vuex';
import daterange from '../daterange';
import { dataScope } from '../../config/util';

export default {
	name: 'pricecalendar',

	data () {
		return {
			week : ["日", "一", "二", "三", "四", "五", "六"],

			weekDay : [
		    	{ day: '日', value: true },
		        { day: '一', value: true },
		        { day: '二', value: true },
		        { day: '三', value: true },
		        { day: '四', value: true },
		        { day: '五', value: true },
		        { day: '六', value: true },
		    ],

			pricecalendarData : {
				y : '',
				m : '',
				data : [],
			},
			
			sa : this.showattrarr,

			batchSetupFormVisible : false,

			batchSetupForm : {
				s_e : [new Date(), new Date()],
				week : [0, 1, 2, 3, 4, 5, 6],
				guide_price : 0,
				cost_price : 0,
				num : 0,
				date : '',//clickWhat == 1 时有用
			},

			//0：批量设置，1：单个设置
			clickWhat : 0,
		}
	},

	components: {
		daterange,
	},

	props: {
	  	showattrarr : Array,
	  	dayprice : Array,
	  	attrid : String,
	  	refresh : Number,
	},

	computed : {

		dp () {
			var dataobj = {};
			for(var i = 0; i < this.dayprice.length; i++){
				var tmp = this.dayprice[i];
				dataobj[tmp.date] = tmp;
			}
			return dataobj;
		},


		mmm () {
			console.log(this.refresh);
			return this.makedata(this.pricecalendarData.y, this.pricecalendarData.m, this.dp, this.sa);
		},
	},

	methods : {
		makedata (year, month, dataobj, showattrarr) {

			var montharray = [31,28,31,30,31,30,31,31,30,31,30,31];
		
			var obj = {
				'y' : year,
				'm' : month,
				'data' : [],
			};

			if((obj.m === 1) && (obj.y % 4 === 0) 
			&&((obj.y % 100 !== 0) || (obj.y % 400 === 0)))
	        {
	            montharray[1] = 29;
	        }

	        //1号
	        var firstdate = new Date(obj.y, obj.m ,1);
	        //最后一号
	        var lastdate = new Date(obj.y, obj.m, montharray[obj.m]);

	        //1号星期几
	        var fxingqi = firstdate.getDay();
	        //最后一号星期几
	        var lxingqi = lastdate.getDay();

	        var dataarr = [];
	        //日期之前的空位
	        for(var f = 0; f < fxingqi; f++)
	        {
	            var dayobj = {
	                'label' : '',
	                'd' : '0',
	            };
	            dataarr.push(dayobj);
	        }
	        //日期
	        for(var j = 0; j < montharray[obj.m]; j++)
	        {
	            var dayobj = {
	                'label' : j + 1,
	                'd' : obj.y + '-',
	                'labelarr' : [],	//具体显示的信息
	            };

	            if(obj.m < 9){
	            	dayobj.d += '0' + (obj.m + 1);
	            }else{
	            	dayobj.d += obj.m + 1;
	            }

	            if(j < 9){
	            	dayobj.d += '-0' + (j+1);
	            }else{
	            	dayobj.d += '-' + (j+1);
	            }

	            //有数据要显示。
	            var show = dataobj[dayobj.d];
	            if(dataobj[dayobj.d] != undefined){
	            	for(var x = 0; x < showattrarr.length; x++){
	            		var xx = showattrarr[x];
	            		var ooo = {
		            		'show' : (xx.before || '') + show[xx.key] + (xx.after || ''),
		            		'position' : xx.position
		            	};
	            		dayobj.labelarr.push(ooo);
	            		dayobj['data'] = show;
	            	}
	            }
	            dataarr.push(dayobj);
	        }
	        //日期之后的空位
	        for(var l = lxingqi; l < 6; l++)
	        {
	            var dayobj = {
	                'label' : '',
	                'd' : '0',
	            };
	            dataarr.push(dayobj);
	        }

	        for(var i = 0; i < dataarr.length; i++){
	        	//每七个重新组装一个数组。
	        	var x = i % 7;
	        	if(x === 0){
	        		obj.data.push(new Array());
	        	}
	        	obj.data[obj.data.length - 1].push(dataarr[i]);
	        }
	        return  obj;

		},

		//step 负数，之前几个月，-1：表示之前一个月
		//     正数，之后几个月，1 ：表示之后一个月
		getYM (y, m, step) {
			
			var yy = y;
			var mm = m;

			if(mm + step < 0){
				yy -= 1;
				mm = 12 + mm + step;
			}else if(mm + step > 11){
				yy += 1;
				mm = mm + step - 12;
			}else{
				mm += step;
			}

			return {
				'y' : yy,
				'm' : mm,
			}
		},

		pre () {

			var dd = this.getYM(this.pricecalendarData.y, this.pricecalendarData.m, -1);
			this.pricecalendarData.y = dd.y;
			this.pricecalendarData.m = dd.m;
		},

		back () {
			var dd = this.getYM(this.pricecalendarData.y, this.pricecalendarData.m, 1);
			this.pricecalendarData.y = dd.y;
			this.pricecalendarData.m = dd.m;
		},

		cellClick (row, column, cell, event) {
			let index = 0;
			for(let i = 0; i < this.week.length; i++){
				if(column.label == this.week[i]){
					index = i;
					break;
				}
			}

			this.clickWhat = 1;
			var obj = row[index].data;
			console.log(row[index]);
			console.log(obj);

			if(obj != undefined){
				this.batchSetupForm.guide_price = obj.guide_price;
				this.batchSetupForm.cost_price = obj.cost_price;
				this.batchSetupForm.num = obj.current_stock_num;
				this.batchSetupForm.date = obj.date;
			}else{

				if(row[index].d == 0){
					this.$notify({
			          title: '警告',
			          message: '请选择当月日期',
			          type: 'warning'
			        });
			        return;
				}

				this.batchSetupForm.guide_price = 0;
				this.batchSetupForm.cost_price = 0;
				this.batchSetupForm.num = 0;
				this.batchSetupForm.date = row[index].d;
			}

			this.batchSetupFormVisible = true;

		},

		cellSave () {

			var result = {
				list : [],
				cb : res => {
					this.$notify({
			          title: '成功',
			          message: '操作成功',
			          type: 'success'
			        });
			        this.batchSetupFormVisible = false;
				}
			};

			var p = {
				'attr_id' : this.attrid,
    			'date' : this.batchSetupForm.date,
    			'market_price' : 0,
    			'guide_price' : this.batchSetupForm.guide_price,
    			'cost_price' : this.batchSetupForm.cost_price,
    			'current_stock_num' : this.batchSetupForm.num,
			};
			var dd = this.dp[this.batchSetupForm.date];
			if(dd){
				p['id'] = dd.id;
			}

			result.list.push(p);

			this.$emit('batchsetup-save', result);
		},

		cellDel () {

			this.$confirm('此操作将删除该天价格, 是否继续?', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	var result = {
						list : [],
						cb : res => {
							this.$notify({
					          title: '成功',
					          message: '操作成功',
					          type: 'success'
					        });
					        this.batchSetupFormVisible = false;
						}
					} 

					var dd = this.dp[this.batchSetupForm.date];
					var p = {
						'attr_id' : this.attrid,
		    			'date' : this.batchSetupForm.date,
		    			'guide_price' : this.batchSetupForm.guide_price,
    					'cost_price' : this.batchSetupForm.cost_price,
		    			'state' : '1',
		    			'id' : dd.id
					};

					result.list.push(p);

					this.$emit('batchsetup-save', result);
		        }).catch(() => {
		                  
		    });

		},

		batchSetup () {
			this.batchSetupForm.guide_price = 0;
			this.batchSetupForm.cost_price = 0;
			this.batchSetupForm.num = 0;
			this.batchSetupForm.date = '';

			this.clickWhat = 0;

			this.batchSetupFormVisible = true;
		},

		batchSetupSave () {
			var datearr = dataScope(this.batchSetupForm.s_e[0], this.batchSetupForm.s_e[1]);
			var result = {
				list : [],
				cb : res => {
					this.$notify({
			          title: '成功',
			          message: '操作成功',
			          type: 'success'
			        });
			        //this.initDate();
			        this.batchSetupFormVisible = false;
				}
			}
			for (var i = 0; i < datearr.length; i++){
				var tmp = datearr[i];
				var day = new Date(tmp).getDay();

				if(!this.weekDay[day].value){
					continue;
				}

				var p = {
					'attr_id' : this.attrid,
	    			'date' : tmp,
	    			'market_price' : 0,
	    			'guide_price' : this.batchSetupForm.guide_price,
	    			'cost_price' : this.batchSetupForm.cost_price,
	    			'current_stock_num' : this.batchSetupForm.num,
				};
				var dd = this.dp[tmp];
				if(dd){
					p['id'] = dd.id;
				}
				result.list.push(p);
			}
			this.$emit('batchsetup-save', result);
		},

		batchSetupDel () {
			this.$confirm('此操作将删除这段时间价格, 是否继续?', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	var datearr = dataScope(this.batchSetupForm.s_e[0], this.batchSetupForm.s_e[1]);
					var result = {
						list : [],
						cb : res => {
							this.$notify({
					          title: '成功',
					          message: '操作成功',
					          type: 'success'
					        });
					        //this.initDate();
					        this.batchSetupFormVisible = false;
						}
					}
					for (var i = 0; i < datearr.length; i++){
						var tmp = datearr[i];
						var day = new Date(tmp).getDay();

						if(!this.weekDay[day].value){
							continue;
						}
						
						var dd = this.dp[tmp];
						if(dd){
							var p = {
								'attr_id' : this.attrid,
				    			'date' : tmp,
				    			'id' : dd.id,
				    			'state' : '1',
							};
							result.list.push(p);
						}
						
					}
					this.$emit('batchsetup-save', result);
		        }).catch(() => {
		                  
		    });
		},

		initDate() {
			console.log('mounted');
			var date = new Date();
			this.pricecalendarData.y = date.getFullYear();
	    	this.pricecalendarData.m = date.getMonth();
		},
	},

	watch:{
	    
	},

	mounted () {
		this.initDate();
	},

}
</script>

<style scope>
.fc-toolbar {
	height: 50px;
	background-color: #23b7e5;
	color: #fff;
	border-radius: 3px 3px 0 0;
	text-align: center;
	padding-top: 15px;
}

.el-table th  {
	text-align: center;
	/*color : red;*/
}

.haha {
	min-height: 50px;
}
</style>
